var urlDetail = server_host + '/userweb/getUserOrderDetail.do';
//获取微信预支付信息
var urlWxPrePayInfo = domain_url + '/h5wx/getWXpayInfo.do';
//退订
var urlUnsubscribe = server_host + '/userweb/cancelTableOrder.do';
//剩余时间为0重加载数据
var urlReLoad = server_host + '/user/cancelTableOrder.do';
//订单号
var orderNum = getParameterByName('orderNum');
// 取shopId
var shopId = sessionStorage.getItem('shopId');
// 状态
var stateCode = getParameterByName('stateCode');
//发起微信支付
var urlWxPrePay = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx497e8037bea463e7&redirect_uri=http://www.cheerhi.com/h5wx/callwxpay.do' + encodeURIComponent('?url=order-details.html') + '&response_type=code&scope=snsapi_base&state=' + orderNum + '#wechat_redirect';

//是否来自微信支付回调
var fromWxPay = getParameterByName('fromWxPay');

// 红包数额
var ticketValue = getParameterByName('ticketValue');


// 分享接口(20151008新加)
var urlCreateShareCoupon = server_host + '/uweb/coupon/order/createShareCoupon.do';

var appModule = angular.module('CheerHiWx', []);
appModule.controller('OrderDetailCtrl', ['$scope', '$http', function($scope, $http) {

	$scope.ticketValue = ticketValue;
	$scope.orderNum = orderNum;

	$scope.orderStatusArr = [{
		code: 1,
		dscp: '订单未付款，未消费',
		refundBtn: true,
		payBtn: true
	}, {
		code: 2,
		dscp: '订单未付款，已消费',
		refundBtn: false,
		payBtn: true
	}, {
		code: 3,
		dscp: '订单已付款，未消费',
		refundBtn: true,
		payBtn: false
	}, {
		code: 4,
		dscp: '订单已付款，已消费',
		refundBtn: false,
		payBtn: false
	}, {
		code: 5,
		dscp: '退款中',
		refundBtn: false,
		payBtn: false
	}, {
		code: 6,
		dscp: '已退订',
		refundBtn: false,
		payBtn: false
	}, {
		code: 7,
		dscp: '已退款',
		refundBtn: false,
		payBtn: false
	}, {
		code: 8,
		dscp: '待现场付,未消费',
		refundBtn: true,
		payBtn: false
	}, {
		code: 9,
		dscp: '待现场付,已消费',
		refundBtn: false,
		payBtn: false
	}, {
		code: 10,
		dscp: '已现场付,已消费',
		refundBtn: false,
		payBtn: false
	}];

	$scope.toDate = function(datetimeStr){
		var date = new Date();
		var dateStr = datetimeStr.split(' ')[0];
		var timeStr = datetimeStr.split(' ')[1];
		date.setFullYear(dateStr.split('-')[0]);
		date.setMonth(dateStr.split('-')[1] - 1);
		date.setDate(dateStr.split('-')[2]);
		date.setHours(timeStr.split(':')[0]);
		date.setMinutes(timeStr.split(':')[1]);
		date.setSeconds(timeStr.split(':')[2]);
		return date;
	}

	$scope.showTime = false;

	$scope.loadDetails = function() {
		$http.get(urlDetail + '?orderNum=' + orderNum).success(function(data, status, headers, config) {
			console.log(data);
			$scope.orderDetails = data.data;
			$scope.orderStatus = findElement($scope.orderStatusArr, 'code', data.data.stateCode);

			// $scope.orderDetails.createTime = '2015-09-02 21:37:45';

			if(($scope.toDate($scope.orderDetails.lastTime).getTime() - (new Date()).getTime() < 15 * 1000 * 60) && ($scope.toDate($scope.orderDetails.lastTime).getTime() - (new Date()).getTime() >= 0)){
				$scope.showTime = true;
				// 倒计时
				// var datetimeStr = '2015-09-02 21:37:45';
				var datetimeStr = $scope.orderDetails.lastTime;
				//创建时间
				// var date = $scope.toDate(datetimeStr);
				//取消时间（十五分钟以后）
				$scope.expiryTime = $scope.toDate(datetimeStr);

				$scope.setLimiteTime = setInterval(function(){

					var currTime = new Date();
					var times = $scope.expiryTime.getTime() - currTime.getTime();
					var minutes = parseInt(times / (1000 * 60));
					var seconds = parseInt(times % (1000 * 60));
					// console.log(minutes + ':' + parseInt(seconds / 1000));

					if(times<=0 && stateCode==1){
						clearInterval($scope.setLimiteTime);
						$scope.limitTime = "00:00";
						// 剩余时间为0重加载数据
						$http.get(urlReLoad + '?orderNum=' + $scope.orderDetails.orderNum).success(function(data, status, headers, config){
							$scope.loadDetails();
						})
					}else{
						$scope.limitTime = minutes + ':' + parseInt(seconds / 1000);
					}
					$scope.$apply();

				},1000);
			}

		});
	}

	// 退订
	$scope.unsubscribe = function(orderNum) {
		var r=confirm("确定退单?");
		if (r==true){
	    	$http.post(urlUnsubscribe + '?orderNum=' + orderNum).success(function(data, status, headers, config) {
				console.log(data);
				if (data.data.isSuccess) {
					alert(data.data.msg);
					$scope.loadDetails();
				}
			});
	    }
	}

	// 退款
	$scope.refund = function() {
		location.href = 'order_details_refund.html?params=' + jsonObjToBase64({
			orderNum: $scope.orderDetails.orderNum,
			tradeNo: $scope.orderDetails.tradeNo,
			orderPrice: $scope.orderDetails.price
		});
	}

	// 去支付
	$scope.goPay = function() {
		location.href = 'pay-way.html?orderNum=' + orderNum;
	}

	// 点击『地图』
	$scope.openmap = function() {
		// location.href = 'map.html?shopId=' + shopId + '&shopName=' + $scope.shopDetails.shopName + '&lat=' + $scope.shopDetails.lat + '&lng=' + $scope.shopDetails.lng; 
		wx.openLocation({
			latitude: parseFloat($scope.orderDetails.lat),
			longitude: parseFloat($scope.orderDetails.lng),
			name: $scope.orderDetails.shopName,
			address: $scope.orderDetails.addr,
			scale: 20,
			infoUrl: ''
		});
	}

	$scope.loadDetails();

}]);

// 判断红包分享模态框是否弹出(20151008新加)
$('#share').on('shown.bs.modal',function(){
    wxJssdkInit2();
    console.log(1);
})

$('#share').on('hidden.bs.modal', function () {
    wxJssdkInit();
    console.log(2);
})

// 分享订单
function wxJssdkInit() {
	$.ajax({
		type: 'POST',
		dataType: 'json',
		url: server_host + '/h5wx/getWxTicket.do?url=' + encodeURIComponent(location.href.split('#')[0]),
		success: function(data) {
			wx.config({
				debug: false,
				appId: wxAppId,
				timestamp: data.timestamp,
				nonceStr: data.nonceStr,
				signature: data.signature,
				jsApiList: wxJsApi
			});
			var orderDetails = angular.element(document.body).scope().orderDetails;
			wx.onMenuShareAppMessage({
				title: orderDetails.shareTitle, // 分享标题
				desc: orderDetails.shareContent, // 分享描述
				link: orderDetails.shareUrl, // 分享链接
				imgUrl: orderDetails.shareImg, // 分享图标
				type: 'link', // 分享类型,music、video或link，不填默认为link
				dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
				success: function() {
					alert('分享成功！');
				},
				cancel: function() {
					// 用户取消分享后执行的回调函数
				}
			});
			wx.onMenuShareTimeline({
				title: orderDetails.shareTitle, // 分享标题
				link: orderDetails.shareUrl, // 分享链接
				imgUrl: orderDetails.shareImg, // 分享图标
				success: function() {
					alert('分享成功！');
				},
				cancel: function() {
					// 用户取消分享后执行的回调函数
				}
			});
			wx.onMenuShareQQ({
				title: orderDetails.shareTitle, // 分享标题
				desc: orderDetails.shareContent, // 分享描述
				link: orderDetails.shareUrl, // 分享链接
				imgUrl: orderDetails.shareImg, // 分享图标
				success: function() {
					alert('分享成功！');
				},
				cancel: function() {
					// 用户取消分享后执行的回调函数
				}
			});
		}
	});
}
// 微信分享红包(20151008新加)
function wxJssdkInit2() {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: server_host + '/h5wx/getWxTicket.do?url=' + encodeURIComponent(location.href.split('#')[0]),
        success: function(data) {
            wx.config({
                debug: false,
                appId: wxAppId,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                jsApiList: wxJsApi
            });
            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: urlCreateShareCoupon + '?orderNum=' + orderNum,
                success: function(data) {
                    console.log(data);
                    wx.onMenuShareAppMessage({
                        title: data.data.title, // 分享标题
                        desc: data.data.context, // 分享描述
                        link: data.data.shareUrl, // 分享链接
                        imgUrl: data.data.img, // 分享图标
                        type: 'link', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function() {
                            alert('分享成功！');
                        },
                        cancel: function() {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    wx.onMenuShareTimeline({
                        title: data.data.title, // 分享标题
                        link: data.data.shareUrl, // 分享链接
                        imgUrl: data.data.img, // 分享图标
                        success: function() {
                            alert('分享成功！');
                        },
                        cancel: function() {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    wx.onMenuShareQQ({
                        title: data.data.title, // 分享标题
                        desc: data.data.context, // 分享描述
                        link: data.data.shareUrl, // 分享链接
                        imgUrl: data.data.img, // 分享图标
                        success: function() {
                            alert('分享成功！');
                        },
                        cancel: function() {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                }
            })
        }
    });
}

if (typeof WeixinJSBridge == "undefined") {
	if (document.addEventListener) {
		document.addEventListener('WeixinJSBridgeReady', wxJssdkInit, false);
	} else if (document.attachEvent) {
		document.attachEvent('WeixinJSBridgeReady', wxJssdkInit);
		document.attachEvent('onWeixinJSBridgeReady', wxJssdkInit);
	}
} else {
	wxJssdkInit();
}